<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="s_id" label="试卷ID">
				<uni-easyinput v-model="formData.s_id"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="name" label="试卷昵称">
				<uni-easyinput v-model="formData.name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="paper_local" label="定位">
				<uni-easyinput v-model="formData.paper_local"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="video_link" label="视频">
				<uni-data-checkbox :multiple="true" v-model="formData.video_link"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="video_name" label="视频">
				<uni-data-checkbox :multiple="true" v-model="formData.video_name"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="quesction_list" label="题目集合">
				<uni-data-checkbox :multiple="true" v-model="formData.quesction_list"></uni-data-checkbox>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/test-paper.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'test-paper';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				"s_id": "",
				"name": "",
				"paper_local": "",
				"video_link": [],
				"video_name": [],
				"quesction_list": []
			}
			return {
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				value.sid = Number(value.s_id)
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>
